<?php


namespace App\Http\Controllers\User\userCenter;


use App\Http\Controllers\Controller;
use App\Services\MemberService;
use App\Services\UserLevelService;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class IndexController extends Controller
{
    public function index()
    {
        // Cookie::queue('token', '537ed4a6e9f4eeedb4f985e48db61f3464e19ef7d6685');
        // Cookie::queue('user_id', 147275, $minutes = 0, $path = null, $domain = null, $secure = false, $httpOnly = false);
        // return 665;
        $uid = Cookie::get('user_id');
        if (!$uid) {
            return redirect()->route('index');
        }
        $dhBalance = DB::table('sys_config')->where('key', 'dh_balance')->value('value');
        return view('user.user_center', [
            'uid' => $uid,
            'dh_balance' => $dhBalance,
        ]);
    }

    /**
     * 获取用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo(Request $request)
    {
        $user = $request->userInfo;
        $levelList = DB::table('user_level')->orderBy('need_money', 'desc')->get();
        $curLevel = [];
        $nextLevel = $levelList[0];
        foreach ($levelList as $item) {
            if ($item->id == $user->level_id) {
                $curLevel = $item;
            }
            if ($item->need_money > $user->total_recharge) {
                $nextLevel = $item;
            }
        }
        return successResp([
            'user' => [
                'id' => $user->id,
                'wx_unionid' => $user->unionid,
                'username' => $user->username,
                'money' => $user->money,
                'ly_balance' => $user->ly_balance,
                'mobile' => $user->mobile,
                'id_card' => $user->id_card,
                'integral' => $user->integral,
                'total_recharge' => $user->total_recharge,
                'unionid' => $user->unionid,
                'wf_integral' => $user->wf_integral,
            ],
            'cur_level' => $curLevel,
            'next_level' => $nextLevel
        ]);
    }

    /**
     * 用户等级
     * @return \Illuminate\Http\JsonResponse
     */
    public function getLevelList(Request $request)
    {
        // 5级以内只有5级，后面的多一级
        $user = $request->userInfo;
        $levelId = 8;
        if ($user && $user->level_id > 8) {
            $levelId = $user->level_id;
        }
        $list = DB::table('user_level')
            ->where('id', '<=', $levelId < 8 ? 8 : $levelId + 1)
            ->orderBy('need_money', 'asc')->get();
        return successResp($list);
    }

    public function loginOut()
    {
        Cookie::queue('token', '');
        Cookie::queue('user_id', '');
        return successResp('');
    }

    /**
     * 意见建议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function commitYj(Request $request)
    {
        $this->validate($request, [
            'yj' => ['string', 'required'],
            'mobile' => ['string', 'required'],
        ]);
        $userInfo = $request->userInfo;
        $data = [
            'union_id' => $userInfo->unionid,
            'content' => $request->yj,
            'mobile' => $request->mobile,
            'create_time'=>date('Y-m-d H:i:s')
        ];
        DB::table('yjjy')->insert($data);
        // 发送模板消息
        sendRechargeWxTemplateMsg('oohRU6YtZttn5auL0FKPr2pS5ryU', '收到新建议', '收到新建议', 0, 0);
        return successResp('');
    }

    /**
     * 邀请记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInviteeList(Request $request)
    {
        $userInfo = $request->userInfo;
        $list = DB::table("users")->where('from_id', $userInfo->id)
            ->orderBy('id', 'desc')
            ->select(['id', 'unionid', 'username', 'mobile', 'created_at'])
            ->get();
        return successResp($list);
    }

    /**
     * 最近在玩
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getLastGame(Request $request)
    {
        $userInfo = $request->userInfo;
        $gameIds = DB::table('draw_log')
            ->where('user_id', $userInfo->id)
            ->where('draw_id', 0)
            ->groupBy('game_id')
            ->pluck('game_id')->toArray();
        if (count($gameIds) > 5) {
            $gameIds = array_slice($gameIds, -5);
        }
        $list = DB::table('game_data')
            ->whereIn('id', $gameIds)
            ->select(['id', 'server_name', 'server_ip', 'image', 'url'])
            ->get();
        $dj = DB::table('game_data')
            ->select(['id', 'server_name', 'server_ip', 'image', 'url'])
            ->orderBy('id', 'desc')
            ->limit(5)
            ->get();
        return successResp(['zj'=>$list, 'dj'=>$dj]);
    }

    /**
     * 实名认证
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function realName(Request $request)
    {
        $this->validate($request, [
            'idcard' => ['string', 'required'],
            'name' => ['string', 'required'],
        ]);
        $userInfo = $request->userInfo;
        if ($userInfo->id_card) {
            return errorResp('已进行实名认证');
        }
        DB::table("users")->where('id', $userInfo->id)->update([
            'id_card' => $request->idcard
        ]);
        // 增加用户乐游币
        MemberService::setMemberBalance(
            $userInfo,
            MemberService::BalanceTypeLy,
            MemberService::FromTypeRealName,
            0,
            1000,
            '实名认证奖励'
        );
        // 给上级增加
        if ($userInfo->from_id) {
            $p = DB::table('users')->find($userInfo->from_id);
            MemberService::setMemberBalance(
                $p,
                MemberService::BalanceTypeLy,
                MemberService::FromTypeSubRealName,
                $userInfo->id,
                1000,
                '好友实名认证奖励'
            );
        }
        return successResp([]);
    }

    /**
     * 刷新用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function refreshUserInfo(Request $request)
    {
        MemberService::refreshLevel($request->userInfo);
        return successResp('');
    }

    /**
     * 玩服积分列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function wfIntegralList(Request $request)
    {
        $user = $request->userInfo;
        $list = DB::table('user_balance_log')
            ->where('unionid', $user->unionid)
            ->where('balance_type', MemberService::BalanceTypeWf)
            ->orderBy('id', 'desc')
            ->limit(20)
            ->get();
        foreach ($list as $v) {
            $v->create_time = date('Y-m-d H:i:s', $v->create_time);
        }
        return successResp($list);
    }

    /**
     * 获取邀请二维码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInviteCode(Request $request)
    {
        $user = $request->userInfo;
        header("Access-Control-Allow-Origin:*");
        $config = config('wechat');
        $app = Factory::officialAccount($config);
        $result = $app->qrcode->temporary("bind_{$user->id}", 86400*7);
        return successResp($result);
    }

    /**
     * 是否需要更换客服
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNeedBindKf(Request $request)
    {
        $resp = ['needChange' => false, 'kfList' => [], 'canChange' => false];
        $user = $request->userInfo;
        // 当前等级是否能绑定客服
        $canBindKfLevel = DB::table('customer_service_level')
            ->where('start_vip', '<=', $user->level_id)
            ->where('end_vip', '>=', $user->level_id)
            ->first();
        if (!$canBindKfLevel) {
            return successResp($resp);
        }
        $kfList = DB::table('customer_service')->where('level_id', $canBindKfLevel->id)->get();
        if (!$kfList->count()) {
            return successResp($resp);
        }
        $resp['canChange'] = true;
        // 查询是否有客服
        $curKfId = DB::table('customer_service_user')
            ->where('unionid', $user->unionid)
            ->value('service_id');
        $resp['needChange'] = true;
        $resp['kfList'] = $kfList;
        if (!$curKfId) {
            return successResp($resp);
        }
        // 当前客服是否需要更换
        foreach ($kfList as $kf) {
            if ($kf->id === $curKfId) {
                $resp['needChange'] = false;
            }
        }
        return successResp($resp);
    }

    /**
     * 获取客服二维码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getKfQrCode(Request $request)
    {
        $kfId = $request->get('admin_id', 0);
        header("Access-Control-Allow-Origin:*");
        $config = config('wechat');
        $app = Factory::officialAccount($config);
        $result = $app->qrcode->temporary("ctmSer_{$kfId}", 86400*7);
        return successResp($result);
    }


    /**
     * 测试token
     */
    public function setTestToken()
    {
        $user = DB::table('users')->find(147275);
        Cookie::queue('token', $user->token);
        Cookie::queue('user_id', 147275, $minutes = 0, $path = null, $domain = null, $secure = false, $httpOnly = false);
        echo 'success';
    }
}
